package org.phalanx.client.net;

import java.util.Date;

import org.phalanx.messenging.PingTimeMessage;
import org.phalanx.messenging.management.MessageListener;
import org.phalanx.messenging.management.PhalanxMetaMessage;

public class KeepAliveThread extends Thread implements MessageListener {
	private boolean threadState;
	private boolean isTimeOut;
	private long sendTime;
	private PhalanxConnectionManager connMgr;

	public KeepAliveThread(PhalanxConnectionManager connMgr){
		setThreadState(true);
		setTimeOut(false);
		this.connMgr = connMgr;
	}
	
	
	public void startKeepAlive() {
		setThreadState(true);
		
		try {
			while(threadState && !isTimeOut) {
				PingTimeMessage pingMsg = new PingTimeMessage();
				pingMsg.setAction(PingTimeMessage.PING_REQUEST);
				//connMgr.getMessageManager().sendMessage(pingMsg, connMgr.createChatObject(connMgr.getServerNode()));
				sendTime = new Date().getTime();
				Thread.sleep(15000);
			}
		}catch (InterruptedException ie){
			setThreadState(false);
		}
	}

	public void setThreadState(boolean state) {
		threadState = state;
	}
	
	private void setTimeOut(boolean timeOut) {
		isTimeOut = timeOut;
	}
	
	public void processMessage(PingTimeMessage msg, PhalanxMetaMessage pMsg) {
		if (msg.getAction() != null) {
			if (msg.getAction().equals(PingTimeMessage.PING_REPLY)) {
				long receiveTime = new Date().getTime();
				long latency = receiveTime - sendTime;
				System.out.println(latency + "");
				if (latency >= PhalanxConnectionManager.TIME_OUT) {
					setThreadState(false);
					connMgr.setConnectionState(false);
				}
			}
		}
	}


	@Override
	public void run() {
		startKeepAlive();
	}
}